package red.yancloud.www.ui.read

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.viewpager.widget.ViewPager
import com.alibaba.fastjson.JSONObject
import com.dyhdyh.widget.loading.dialog.LoadingDialog
import com.flyco.tablayout.listener.OnTabSelectListener
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.ig.DefaultImageGetter
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_read_epup.*
import okhttp3.ResponseBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import red.yancloud.www.R
import red.yancloud.www.common.Constants
import red.yancloud.www.common.MessageEvent
import red.yancloud.www.db.sharedpreference.ReadSettingShardPreference
import red.yancloud.www.db.sharedpreference.UserInfoShardPreference
import red.yancloud.www.internet.api.RedCloudApis
import red.yancloud.www.internet.bean.BookEntity
import red.yancloud.www.internet.bean.BookMarkEntity
import red.yancloud.www.internet.bean.Chapter
import red.yancloud.www.manager.DatabaseManager
import red.yancloud.www.manager.ThemeManager
import red.yancloud.www.ui.adapter.ViewPagerFragmentAdapter
import red.yancloud.www.ui.dialog.BookReadSettingDialog
import red.yancloud.www.ui.dialog.LoadingCallback
import red.yancloud.www.ui.fragment.BookCatalogFragment
import red.yancloud.www.util.NetworkUtils
import red.yancloud.www.util.ScreenUtils
import red.yancloud.www.util.TimeFormatUtil
import red.yancloud.www.util.ToastUtils
import taobe.tec.jcc.JChineseConvertor
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs
import kotlin.math.roundToInt

/**
 * @Org：www.shuhai.com(陕西书海网络科技有限公司)
 * @Author：风不会停息 on 2019/6/21 14:40
 * E_Mail：yh131412hys@163.com
 * Describe：EPup阅读界面
 * Change：
 * @Version：V1.0
 */
class EPupReadActivity : AppCompatActivity(), OnDrawerPageChangeListener {

    private val TAG = "EPupReadActivity"

    private lateinit var loadingDialog: Dialog
    private var mScreenWidth: Int = 0
    private var mScreenHeight: Int = 0
    private lateinit var readSetting:ReadSettingShardPreference
    private lateinit var lp: WindowManager.LayoutParams
    private val lineSpace:Float = 6.0f
    private var textViewLineHeight:Int = -1
    private var textViewLineCount:Int = -1
    private var scrollY: Int = -1
    private var isScroll:Boolean = true
    private var currentProgress: Int = 0
    //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
    private var x1:Float = 0F
    private var y1:Float = 0F
    private var x2:Float = 0F
    private var y2:Float = 0F

    private var queryBookInfo:BookEntity?=null
    lateinit var bookId:String
    private lateinit var firstbookchapterid:String
    private var preCid:String = ""
    private var currentCid:String = ""
    private var nextCid:String = ""
    private var title:String=""
    private var bookName:String=""
    private var content:String=""

    private val mTitles = arrayOf("目录", "书签")
    lateinit var mViewPager: ViewPager
    lateinit var mDrawerLayout: DrawerLayout

    fun getScroll_Y() :Int{

        return scrollY
    }

    fun getCurrentCid() :String{

        return currentCid
    }

    fun getChapterName() :String{

        return title
    }

    fun getCurrentProgress() :Int{

        return currentProgress
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_read_epup)

        EventBus.getDefault().register(this)

        mScreenWidth = ScreenUtils.getScreenWidth()
        mScreenHeight = ScreenUtils.getRealHeight()

        Log.d(TAG,"mScreenWidth:$mScreenWidth--------------mScreenHeight:$mScreenHeight")

        initData()
        initView()
        initSmartRefreshLayout()
    }

    private fun initData() {

        loadingDialog = LoadingDialog.make(this, LoadingCallback()).create()
        loadingDialog.setCancelable(true)
        loadingDialog.setCanceledOnTouchOutside(true)

        readSetting = ReadSettingShardPreference.instance
        // 设置阅读排版
        setTypesetting()
        // 设置阅读风格
        setReadStyle(readSetting.readStyle)
        // 设置亮度
        lp = window.attributes
        if (readSetting.systemLight) {
            setScreenMode()
        } else {
            setLight(readSetting.light)
        }

        if (intent.getIntExtra("markType",-1)==1) {

//            目录进入
            val bookMarkEntity = intent.getParcelableExtra<BookMarkEntity>("mark")
            firstbookchapterid=bookMarkEntity.chapterId.toString()
            scrollY=bookMarkEntity.scrollY
        }else{

            bookId = intent.getStringExtra("bookId")
            firstbookchapterid = intent.getStringExtra("firstbookchapterid")
            queryBookInfo = DatabaseManager.instance.queryBookInfo(bookId)
            if (queryBookInfo != null&&!TextUtils.isEmpty(queryBookInfo!!.lastReadBookChapterId)&&queryBookInfo!!.lastReadBookChapterId.toInt()!=0) {

                firstbookchapterid= queryBookInfo!!.lastReadBookChapterId
            }
        }

        //        -2 第一章内容
        getChapterName(firstbookchapterid)
    }

    @TargetApi(Build.VERSION_CODES.M)
    private fun initView() {

        //        章节内容
        contentTv.setOnTouchListener(object :View.OnTouchListener{
            @SuppressLint("ClickableViewAccessibility")
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {

                Log.d("onTouchEvent", event!!.action.toString())

                if (event.action == MotionEvent.ACTION_DOWN) {

                    //当手指按下的时候
                    x1 = event.x
                    y1 = event.y

                    Log.d(TAG,"ACTION_DOWN======x1:$x1======y1:$y1")
                }else if(event.action == MotionEvent.ACTION_UP) {

                    //当手指离开的时候
                    x2 = event.x
                    y2 = event.y

                    Log.d(TAG,"ACTION_UP======x2:$x2======y2:$y2")

                    if (abs(y1 - y2) > 50){
                        return true
                    }

                    if (getTouchLocation(event.x, event.y) == SETTING_AREA && !isFastClick()) {

                        BookReadSettingDialog(this@EPupReadActivity).show()
                    }
                    return true
                }
                return false
            }
        })

        contentTv.viewTreeObserver.addOnGlobalLayoutListener(object :ViewTreeObserver.OnGlobalLayoutListener{
            override fun onGlobalLayout() {

                textViewLineHeight = contentTv.lineHeight
                textViewLineCount = contentTv.lineCount
            }
        })

        contentTv.setOnScrollChangeListener(object :View.OnScrollChangeListener{
            override fun onScrollChange(v: View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {

                Log.d(TAG, "scrollX:$scrollX--scrollY:$scrollY--oldScrollX:$oldScrollX--oldScrollY:$oldScrollY")
                if (textViewLineCount!=-1&&textViewLineHeight!=-1){

//                    Log.d(TAG,"$textViewLineCount----$textViewLineHeight")
//                    Log.d(TAG,"${scrollY / (textViewLineCount * textViewLineHeight * 1.0f)}")
                    this@EPupReadActivity.scrollY=scrollY
                    currentProgress = (scrollY / (textViewLineCount * textViewLineHeight * 1.0f)*100).roundToInt()
//                    Log.d(TAG,"${scrollY / (textViewLineCount * textViewLineHeight * 1.0f)*100}")
                    Log.d(TAG,"$currentProgress")
                }
            }
        })

//        目录、书签
        mViewPager = findViewById(R.id.ePupReadActivity_vP)
        mDrawerLayout = findViewById(R.id.ePupReadActivity_dL)

        val drawerPageChangeListener:OnDrawerPageChangeListener = this

        val bookCatalogFragment = BookCatalogFragment()
        val bookCatalogBundle = Bundle()
        bookCatalogBundle.putString("bookId", bookId)
        bookCatalogFragment.arguments = bookCatalogBundle
//        val bookmarkFragment = BookmarkFragment()
//        val bookmarkBundle = Bundle()
//        bookmarkBundle.putString("bookId", bookId)
//        bookmarkFragment.arguments = bookmarkBundle

        val pagerAdapter = ViewPagerFragmentAdapter(supportFragmentManager)
        pagerAdapter.addFragment(bookCatalogFragment)
//        pagerAdapter.addFragment(bookmarkFragment)
        mViewPager.adapter = pagerAdapter
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {

//                if (position == pagerAdapter.fragmentList.size - 1) {
//                    drawerPageChangeListener.onPageSelected(true)
//                } else {
//                    drawerPageChangeListener.onPageSelected(false)
//                }
//                ePupReadActivity_tL.currentTab = position
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        ePupReadActivity_tL.setTabData(mTitles)
        ePupReadActivity_tL.setOnTabSelectListener(object :OnTabSelectListener{
            override fun onTabSelect(position: Int) {

                mViewPager.currentItem = position
            }

            override fun onTabReselect(position: Int) {

            }
        })
//        titleThemeUpdate(BOOK_CATALOG)

//        mDrawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
//            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
//                //                ToastUtils.showToast("slide");
//            }
//
//            override fun onDrawerOpened(drawerView: View) {
//                //drawer默认打开且锁住，用户不能关闭，但是可以通过代码关闭
//                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN)
//            }
//
//            override fun onDrawerClosed(drawerView: View) {
//                //打开手势滑动
//                mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
//                //                ToastUtils.showToast("close");
//            }
//
//            override fun onDrawerStateChanged(newState: Int) {
//                //                ToastUtils.showToast("change");
//            }
//        })

        // 点击除开侧边栏的区域会收起侧边栏。
        mDrawerLayout.setOnTouchListener(View.OnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> mDrawerLayout.closeDrawers()
            }
            false
        })
    }

    private fun initSmartRefreshLayout() {

        val mClassicsHeader = smartRefreshLayout.refreshHeader as ClassicsHeader
        mClassicsHeader.setLastUpdateTime(Date(System.currentTimeMillis()))
        mClassicsHeader.setTimeFormat(SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA))
        mClassicsHeader.setTimeFormat(TimeFormatUtil("更新于 %s"))

//        smartRefreshLayout.setEnableAutoLoadMore(true)//开启自动加载功能（非必须）
        smartRefreshLayout.setOnRefreshListener(OnRefreshListener {

            if (!NetworkUtils.isConnected(this)) {
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }

            // preCid为0则当前章为第一章 nextCid为0则当前章为最后一章
            if (preCid=="0") {

                ToastUtils.showToast("当前章为第一章,没有上一章了")
                smartRefreshLayout.finishRefresh()
                return@OnRefreshListener
            }
            getChapterName(preCid)
        })
        smartRefreshLayout.setOnLoadMoreListener(OnLoadMoreListener { refreshLayout ->

            if (!NetworkUtils.isConnected(this)) {
                ToastUtils.toastNetErrorMsg()
                smartRefreshLayout.finishLoadMore()
                return@OnLoadMoreListener
            }

            if (nextCid=="0") {

                ToastUtils.showToast("当前章为最后一章,没有下一章了")
                smartRefreshLayout.finishLoadMoreWithNoMoreData()
                return@OnLoadMoreListener
            }
            getChapterName(nextCid)
        })
    }

    override fun onPageSelected(isLast: Boolean) {

        if (isLast) {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
        } else if (mDrawerLayout.getDrawerLockMode(GravityCompat.START) == DrawerLayout.LOCK_MODE_UNLOCKED) {
            mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN)
        }
    }

    /**
     * 设置阅读排版
     */
    private fun setTypesetting() {

        contentTv.setLineSpacing(lineSpace,readSetting.lineSpace)//行间距
//        contentTv.setParagraphSpace(readSetting.getParagraphSpaceBkshop())//段间距
        contentTv.setTextSize(TypedValue.COMPLEX_UNIT_PX,readSetting.textSize.toFloat())//字体大小
//        pageFactory.setLanguage(readSetting.getLanguage())
//        pageFactory.setIndentation(readSetting.getfristLineIndentation())//首航缩进
    }

    /**
     * 设置阅读风格
     */
    private fun setReadStyle(readStyle:Int) {

        when (readStyle) {
            ThemeManager.READ_STYLE_THEME_DEFAULT -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_default))
            }
            ThemeManager.READ_STYLE_THEME_NIGHT -> {

                contentTv.setTextColor(Color.WHITE)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_night))
            }
            ThemeManager.READ_STYLE_THEME_00 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_00))
            }
            ThemeManager.READ_STYLE_THEME_01 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_01))
            }
            ThemeManager.READ_STYLE_THEME_02 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_02))
            }
            ThemeManager.READ_STYLE_THEME_03 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_03))
            }
            ThemeManager.READ_STYLE_THEME_04 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_04))
            }
            ThemeManager.READ_STYLE_THEME_05 -> {

                contentTv.setTextColor(Color.WHITE)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_05))
            }
            ThemeManager.READ_STYLE_THEME_06 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_06))
            }
            ThemeManager.READ_STYLE_THEME_07 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_07))
            }
            ThemeManager.READ_STYLE_THEME_08 -> {

                contentTv.setTextColor(Color.WHITE)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_08))
            }
            ThemeManager.READ_STYLE_THEME_09 -> {

                contentTv.setTextColor(Color.WHITE)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_09))
            }
            ThemeManager.READ_STYLE_THEME_10 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_10))
            }
            ThemeManager.READ_STYLE_THEME_11 -> {

                contentTv.setTextColor(Color.BLACK)
                read_theme_style.setBackgroundColor(resources.getColor(R.color.read_style_theme_11))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)

        Log.d(TAG,"onDestroy-lastReadBookChapterId：$currentCid+scrollY：$scrollY")

        if (queryBookInfo != null) {

            queryBookInfo!!.lastReadBookChapterId=currentCid
            queryBookInfo!!.scrollY=scrollY
            DatabaseManager.instance.updateBookInfo(queryBookInfo!!)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        // 是否音量键翻页
        if (readSetting.soundSwitch) {
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {

                if (preCid=="0") {

                    ToastUtils.showToast("当前章为第一章,没有上一章了")
                    return true
                }
                getChapterName(preCid)
                return true
            } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {

                if (preCid=="0") {

                    ToastUtils.showToast("当前章为最后一章,没有下一章了")
                    return true
                }
                getChapterName(nextCid)
                return true
            }
        }

        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 设置当前屏幕亮度的模式 SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    private fun setScreenMode() {
        try {
            lp.screenBrightness = -1f
            window.attributes = lp
        } catch (localException: Exception) {
            localException.printStackTrace()
        }
    }

    /**
     * 设置屏幕亮度
     */
    private fun setLight(paramInt: Int) {
        // light = readSetting.getLight();// 获取配置文件中的light值
        lp.screenBrightness = paramInt / 255.0f
        window.attributes = lp
    }

    private val MIN_DELAY_TIME = 1000  // 两次点击间隔不能少于1000ms
    private var lastClickTime: Long = 0

    private fun isFastClick(): Boolean {
        var flag = true
        val currentClickTime = System.currentTimeMillis()
        if (currentClickTime - lastClickTime >= MIN_DELAY_TIME) {
            flag = false
        }
        lastClickTime = currentClickTime
        return flag
    }

    // 点击页面区域
    private val PREVIOUS_AREA = 1
    private val NEXT_AREA = 2
    private val SETTING_AREA = 3

    /**
     * 判断点击的区域
     *
     * @param x
     * @param y
     * @return
     */
    private fun getTouchLocation(x: Float, y: Float): Int {
        if (x > mScreenWidth / 4 && x < mScreenWidth * 3 / 4
            && y > mScreenHeight / 4 && y < mScreenHeight * 3 / 4
        ) {
            return SETTING_AREA
        } else if (x > mScreenWidth / 2) {
            return NEXT_AREA
        }
        return PREVIOUS_AREA
    }

    /**
     * 阅读控制
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent){

        when (event.type) {
            Constants.ReadStatus.LOAD_PRE_PAGE-> {

                if (preCid=="0") {

                    ToastUtils.showToast("当前章为第一章,没有上一章了")
                    return
                }
                getChapterName(preCid)
            }
            Constants.ReadStatus.LOAD_NEXT_PAGE -> {

                if (preCid=="0") {

                    ToastUtils.showToast("当前章为最后一章,没有下一章了")
                    return
                }
                getChapterName(nextCid)
            }
            Constants.ReadStatus.READ_STYLE_THEME -> {

                setReadStyle(event.result as Int)
            }
            Constants.ReadStatus.READ_FONT_SIZE -> {

                Log.d(TAG, event.result.toString())
                contentTv.setTextSize(TypedValue.COMPLEX_UNIT_PX,(event.result as Int).toFloat())
            }
            Constants.ReadStatus.LIGHT_LEVEL -> {

                setLight(event.result as Int)
            }
            Constants.ReadStatus.LIGHT_SYSTEM -> {

                if (event.result == Constants.ReadStatus.LIGHT_SYSTEM_OPEN) {
                    setScreenMode()
                } else if (event.result== Constants.ReadStatus.LIGHT_SYSTEM_CLOSE) {
                    setLight(readSetting.light)
                }
            }
            Constants.ReadStatus.READ_LINESPACE -> {

                Log.d(TAG,event.result.toString())
                contentTv.setLineSpacing(lineSpace,event.result as Float)
            }
            Constants.ReadStatus.READ_LANGUANG ->{

                getChapterName(firstbookchapterid)
            }
            Constants.ReadDialogSetting.READ_PROGRESS -> {

                Log.d(TAG,event.result.toString()+"------------"+textViewLineCount+"-----------"+textViewLineHeight)
                Log.d(TAG,((event.result as Int / 100.0f)*textViewLineCount*textViewLineHeight).toString())
                contentTv.scrollY=((event.result as Int / 100f)*textViewLineCount*textViewLineHeight).toInt()
            }
            Constants.ReadStatus.SHARE -> {

                val image = UMImage(this, R.mipmap.ic_launcher)
                val web = UMWeb(/*"http://www.yancloud.red/Yancloudapp/article/?bid=$bookId"*/"http://www.yancloud.red/Portal/Book/info/?id=$bookId") //切记切记 这里分享的链接必须是http开头
                web.title = bookName//标题
                web.setThumb(image)  //缩略图
                web.description = content//描述

                ShareAction(this).withMedia(image).withMedia(web)
                    .setDisplayList(
                        SHARE_MEDIA.SINA,
                        SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                        SHARE_MEDIA.MORE)
                    .setCallback(umShareListener).open()
            }
        }
    }

    private val umShareListener = object : UMShareListener {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        override fun onStart(platform: SHARE_MEDIA) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        override fun onResult(platform: SHARE_MEDIA) {

            ToastUtils.showToast("分享成功了")
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, t: Throwable) {

            ToastUtils.showToast("分享失败" + t.message)
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        override fun onCancel(platform: SHARE_MEDIA) {

        }
    }

    private fun getChapterName(firstbookchapterid: String) {

        loadingDialog.show()

        RedCloudApis.getInstance().chapter(
            UserInfoShardPreference.instance.uid,
            firstbookchapterid,
            bookId,
            object : Observer<ResponseBody> {
                override fun onComplete() {
                }

                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ResponseBody) {

                    val result = String(t.bytes())
                    Log.d(TAG, result)
                    val jsonObject = JSONObject.parseObject(result)
                    val code = jsonObject.getString("code")

                    if (code == Constants.SYSTEM_OK) {

                        val chapterEntity = JSONObject.parseObject(result, Chapter::class.java)

//                        preCid为0则当前章为第一章 nextCid为0则当前章为最后一章
                        preCid = chapterEntity.data.chapter.preCid
                        currentCid = chapterEntity.data.chapter.id
                        nextCid = chapterEntity.data.chapter.nextCid
                        title = chapterEntity.data.chapter.title
                        bookName = chapterEntity.data.book.title
                        content = chapterEntity.data.book.content

                        var content = chapterEntity.data.chapter.content

                        //readActivity_webView.loadDataWithBaseURL(null, t.data.chapter.content, "text/html", "UTF-8", null)
                        if (!TextUtils.isEmpty(content)) {

//                            if (content.contains("<h1>")) {
//
//                                content = content.replace("<h1>", "<p>").replace("</h1>", "</p>")
//                            }
//
//                            if (content.contains("<h2>")) {
//
//                                content = content.replace("<h2>","<p>").replace("</h2>", "</p>")
//                            }
//                            if (content.contains("<h3>")) {
//
//                                content = content.replace("<h3>","<p>").replace("</h3>", "</p>")
//                            }
//                            if (content.contains("<h4>")) {
//
//                                content = content.replace("<h4>","<p>").replace("</h4>", "</p>")
//                            }
//                            if (content.contains("<h5>")) {
//
//                                content = content.replace("<h5>","<p>").replace("</h5>", "</p>")
//                            }
//                            if (content.contains("<h6>")) {
//
//                                content = content.replace("<h6>","<p>").replace("</h6>", "</p>")
//                            }
//                            content = content.replace("\n","")
//                            content = content.trim()

                            Log.d(TAG, content)

                            if (readSetting.language == ReadSettingShardPreference.LANGUAGE_SIMPLIFIED) {

                                RichText.from(content).imageGetter(DefaultImageGetter()).into(contentTv)

                            } else if (readSetting.language == ReadSettingShardPreference.LANGUAGE_TRADITIONAL) {

                                RichText.from(JChineseConvertor.getInstance().s2t(content)).imageGetter(DefaultImageGetter()).into(contentTv)
                            }

                            if (isScroll&&queryBookInfo!=null) {

                                isScroll=false
                                contentTv.scrollY= queryBookInfo!!.scrollY
                            }else{

                                contentTv.scrollY=0
                            }
                        }else{

                            contentTv.text = resources.getString(R.string.current_chapter_no_data)
                        }

                    }else{

                        ToastUtils.showToast(jsonObject.getString("msg"))
                    }

                    smartRefreshLayout.finishRefresh()
                    smartRefreshLayout.finishLoadMore()
                    loadingDialog.dismiss()
                }

                override fun onError(e: Throwable) {

                    smartRefreshLayout.finishRefresh()
                    smartRefreshLayout.finishLoadMore()
                    loadingDialog.dismiss()
                }
            })
    }
}

interface OnDrawerPageChangeListener {
    /**
     * 监听侧边栏的页面选择
     * @param isLast
     */
    fun onPageSelected(isLast: Boolean)
}
